<template>
<view class="container">
  <view v-if="successState=='normal'">
    <view class="userHead">
      <view v-if="mendianImg!=''" class="ListDataItemImage"><image mode="aspectFill" :src="mendianImg"></image></view>
      <view class="mendianText">
        <text style="font-size:30rpx;border-radius:10rpx">
          <text style="padding: 2rpx 16rpx;border-radius:10rpx">{{mendianName}}</text>
        </text>
      </view>
    </view>
    <view class="chongzhijine">
        <view class="pay_money_block">
            <text class="pay_money_text">金额(元)</text>
            <view class="pay_money_input">
                <text class="pay_money_unit">￥</text>
                <input class="pay_money_num" focus @input="getBuyerScript" ></input>
            </view>
        </view>
        <view class="pay_money_remark">
            <textarea class="pay_money_remark_text" @input="getBuyerRemark" placeholder="添加备注(20个字以内)" maxlength="20"></textarea>
        </view>
      <!-- <view class="chongzhijineItem">
        <text style="font-size:26rpx;color:#888">付款金额：</text>
        <input @input="getBuyerScript" placeholder="请输入金额"></input>
      </view>
      <view class="chongzhijineItemRemark">
        <text style="font-size:26rpx;color:#888">备注信息：</text>
        <textarea @input="getBuyerRemark" placeholder="请输入备注信息" maxlength="150"></textarea>
      </view> -->
    </view>
    <view class="way">
        <view class="payName">支付方式</view>
        <radio-group @change="getPayWay">
          <label class="payWay">
            <radio :color="setting.platformSetting.defaultColor" checked="true" value="3"></radio>
            <text>微信支付</text>
          </label>
      <!--   <label class='payWay'>
            <radio color="{{setting.platformSetting.defaultColor}}" checked='false' value='4'></radio>
            <text>支付宝</text>
          </label> -->
        </radio-group>
    </view>
    <view></view>
    <button :loading="butn_show_loading" @tap="subMitButn" class="subMitButn" :style="'background:' + setting.platformSetting.defaultColor">立即付款</button>

    <!--返回首页  -->
      <view class="loginBtnView">
      <button class="loginBtn" @tap="toIndex">返回首页</button> 
    </view>
  </view>
  <!--成功  -->
  <view class="container" v-if="successState=='success'">
    <!--  <view class='addrtop' style='background: {{setting.platformSetting.defaultColor}};'><view></view></view>
      -->
      <view class="successIcon">
        <icon type="success" size="40" :color="setting.platformSetting.defaultColor"></icon>
        <text :style="'color:' + setting.platformSetting.defaultColor + ';margin-left:20rpx;font-size:35rpx'">支付成功</text>
      </view>

      <view class="Items"><text>订单编号: </text>  <text>{{successData.orderNo}}</text></view>  <text></text>
      <view class="Items"><text>订单已付金额: </text> <text>￥ {{successData.goodsAmount}}</text> </view>
      <view class="Items"><text>支付方式: </text>
        <text v-if="successData.payTypeStr=='3'">微信支付</text>
        <text v-if="successData.payTypeStr=='2'">{{properties.alias_yue||'余额'}}支付</text>
        <text v-if="successData.payTypeStr=='9'">积分支付</text>
      </view>
      <view class="Items"><text>备注: </text> <text>{{successData.remark}}</text> </view>
      <!-- <block wx:if='{{success.payType == 2}}'>
        <view class='Items'>充值说明: <text class='main' style="color:{{setting.platformSetting.defaultColor}}"
        bindtap='toAccount'>点击查看{{properties.alias_yue||'余额'}}充值方式</text></view>
      </block> -->

      <button class="butn" @tap="toIndex" :style="'background:' + setting.platformSetting.defaultColor">返回首页</button>
  </view>

</view>
</template>

<script>

export default {
  data() {
    return {
      money: 100,
      payway: 3,
      orderNo: 0,
      butn_show_loading: false,
      mendianId: "",
      mendianImg: "",
      mendianName: "111",
      successState: 'normal',
      remark: "",
      successData: "",
      setting: "",
      properties: "",
      loginUser: ""
    };
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.log(options.id);
    if(getApp().globalData.loginUser){
        that.setData({
          mendianId: options.id
        }); // 获取门店的样式
        
        let menDian = {
          mendianId: options.id
        };
        
        if (getApp().globalData.loginUser) {
          that.getData(menDian);
        } else {
          getApp().globalData.addLoginListener(that); // wx.showLoading({
          //   title: 'loading'
          // })
        
          getApp().globalData.showToastLoading('loading', true);
          console.log("====setTimeout1=====");
          that.setTimeoutLogin(that.conut);
        }
    }else{
        let url="new_pay_offline.html?id="+options.id
        let backUrl=encodeURIComponent(url)
        getApp().globalData.checkIfLogin(backUrl)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.setData({
      setting: getApp().globalData.setting,
      properties: getApp().globalData.properties,
      loginUser: getApp().globalData.loginUser
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},
  methods: {
    // 返回首页
    toIndex: function () {
      getApp().globalData.toIndex();
    },
    login: function (e) {
      wx.switchTab({
        url: '../../pageTab/custom_page_index/index'
      });
    },
    getBuyerScript: function (e) {
      this.setData({
        money: e.detail.value
      });
    },
    getBuyerRemark: function (e) {
      this.setData({
        remark: e.detail.value
      });
    },
    getPayWay: function (e) {
      this.setData({
        payway: e.detail.value
      });
    },
    subMitButn: function () {
      var that = this;
      let money = this.money;
      let payWay = this.payway;
      let remark = this.remark;
      let wxChatPayParam = {
        payAmount: '',
        payType: 3,
        mendianId: that.mendianId
      };
      wxChatPayParam.payAmount = money;
      wxChatPayParam.payType = payWay;
      wxChatPayParam.remark = remark;
      console.log("ff==========", wxChatPayParam);
      this.setData({
        butn_show_loading: true
      });
      let customIndex = getApp().globalData.AddClientUrl("/create_mendian_offline_pay_order.html", wxChatPayParam, 'post');
      console.log("------customIndex.url--------" + JSON.stringify(customIndex.params));
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log("结果" + JSON.stringify(res)); //这里拿到订单数据
          //下面应该吊起支付

          console.log(res.data.relateObj.orderNo);
          let orderNo = res.data.relateObj.orderNo;

          if (!res.data || !res.data.relateObj.payType) {
            console.log('--------失败-------');
          } else if (res.data.relateObj.payType == 3) {
            that.setData({
              orderNo: orderNo
            });
            that.payByWechat(orderNo);
          } else {
            wx.showToast({
              title: '创建订单失败',
              image: '/wxcomponents/images/icons/tip.png',
              duration: 2000
            });
          }
        },
        fail: function () {
          console.log("123456987456321");
        },
        complete: function () {
          that.setData({
            butn_show_loading: true
          });
        }
      });
    },
    payByWechat: function (orderNo) {
      var that = this;
      let loginUser = getApp().globalData.loginUser;
      console.log("loginUser" + loginUser);
      let wxChatPayParam = {
        openid: '',
        orderNo: '',
        app: 3,
        mendianId: that.mendianId
      };
      wxChatPayParam.openid = loginUser.platformUser.miniOpenId;
      wxChatPayParam.orderNo = orderNo;
      console.log("------wxChatPayParam---" + JSON.stringify(wxChatPayParam));
      let customIndex = getApp().globalData.AddClientUrl("/unifined_order.html", wxChatPayParam, 'post');
      console.log("customIndex--------" + JSON.stringify(customIndex));
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log(res.data);
          let PayStr = res.data;
          PayStr = '{' + PayStr + '}';
          let wechatPayStr = JSON.parse(PayStr);
          console.log(wechatPayStr);
          wx.requestPayment({
            'timeStamp': wechatPayStr.timeStamp,
            'nonceStr': wechatPayStr.nonceStr,
            'package': wechatPayStr.package,
            'signType': wechatPayStr.signType,
            'paySign': wechatPayStr.paySign,
            'success': function (res) {
              console.log('------成功--------');
              console.log(res);
              let successData = {
                remark: that.remark,
                orderNo: that.orderNo,
                goodsAmount: that.money,
                payTypeStr: that.payway
              };
              that.setData({
                successData: successData
              });
              that.setData({
                successState: 'success'
              }); // wx.showToast({
              //   title: '支付成功',
              //   icon: 'success',
              //   duration: 2000
              // })
              // 支付成功跳到首页
              // wx.reLaunch({
              //   url: '/pages/success_pay/index',
              // })
            },
            'fail': function (res) {
              console.log('------fail--------');
              console.log(res);
              wx.showToast({
                title: '支付失败',
                image: '/wxcomponents/images/icons/tip.png',
                duration: 2000
              });
            },
            'complete': function () {
              console.log('------complete--------');
              console.log(res);
            }
          });
        }
      });
    },
    loginSuccess: function (user) {
      console.log("pre apply mendian login success call back!", user);
      let that = this;
      let menDian = {
        mendianId: that.mendianId
      };
      that.getData(menDian);
    },
    loginFailed: function (err) {
      console.log("login failed!!");
    },
    setTimeoutLogin: function (conuData) {
      let that = this;
      console.log("====setTimeout-init=====", conuData);
      that.conut = conuData;
      that.conut += 2;

      if (that.conut <= 5) {
        setTimeout(function () {
          if (getApp().globalData.loginUser) {
            wx.hideLoading();
          } else {
            that.setTimeoutLogin(that.conut);
          }
        }, that.conut * 1000);
      } else {
        wx.showModal({
          title: '失败了',
          content: '请求失败了，请下拉刷新！'
        });
      }
    },
    getData: function (menDian) {
      var that = this;
      let menDianYangShi = getApp().globalData.AddClientUrl("/mendian_detail.html", menDian, 'get');
      console.log("customIndex--------" + JSON.stringify(menDianYangShi));
      console.log("customIndex--------" + menDianYangShi.url);
      wx.request({
        url: menDianYangShi.url,
        data: menDianYangShi.params,
        header: getApp().globalData.headerPost,
        method: 'get',
        success: function (res) {
          console.log(res);
          console.log(res.data);

          if (res.data.errcode == "-1") {
            wx.showToast({
              title: res.data.errMessage,
              image: '/wxcomponents/images/icons/tip.png',
              duration: 2000
            });
          } else {
            if (res.data.relateObj.logo == 0) {
              that.setData({
                mendianName: res.data.relateObj.name
              });
            } else {
              var Images = res.data.relateObj.logo;

              if (Images == "") {
                Images = "https://image1.sansancloud.com/xianhua/2020_1/2/18/36/36_931.jpg?x-oss-process=style/preview_120";
              }

              that.setData({
                mendianImg: Images,
                mendianName: res.data.relateObj.name
              });
            }
          }
        }
      });
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>